package spirit.io.nio.ifeve.socketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author eric - 好好学习，天天向上！
 * @date 2022/1/1
 * @description
 */
public class SocketChannelMain {

    public void learn() {
        try {
            // 打开一个SocketChannel， 并连接到互联网上的某一台设备
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.bind(new InetSocketAddress("http://jenkov.com", 80));
            socketChannel.close();

            // 写入数据
            String write = "我要写入到socketChannel";
            ByteBuffer buf = ByteBuffer.allocate(48);
            buf.put(write.getBytes());

            // 反转，将读模式变为写模式
            buf.flip();
            while (buf.hasRemaining()) {
                socketChannel.write(buf);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
